<!-- 代理商表单页面 -->
<template>
	<s-layout :title="isEdit ? '编辑代理商' : '新增代理商'" :bgStyle="{ color: '#FFF' }">
		<view class="form-container">
			<view class="form-section">
				<view class="section-title">基本信息</view>
				<view class="form-content">


					<!-- 用户名称 -->
					<view class="form-item required">
						<view class="form-label">用户名称</view>
						<input class="form-input" placeholder="请输入用户名称（企业名或个人名称）" v-model="state.form.userName"
							maxlength="100" />
					</view>

					<!-- 手机号 -->
					<view class="form-item required">
						<view class="form-label">手机号</view>
						<input class="form-input" :disabled="isEdit.value" placeholder="请输入手机号" v-model="state.form.mobile" type="number"
							maxlength="11" />
					</view>


					<!-- 用户类型 -->
					<view class="form-item required" >
						<view class="form-label">用户类型</view>
						<uni-data-select v-model="state.form.userType" :localdata="state.userTypeOptions">
						</uni-data-select>
					</view>

					<!-- 代理商等级 -->
					<view class="form-item required"
						v-show="state.agentLevelOptions.length > 0 &&  state.form.userType==4">
						<view class="form-label">代理商等级</view>
						<uni-data-select v-model="state.form.agentLevel" :localdata="state.agentLevelOptions">
						</uni-data-select>
					</view>


					<!-- 联系地址 -->
					<view class="form-item">
						<view class="form-label">联系地址</view>
						<input class="form-input" placeholder="请输入联系地址" v-model="state.form.address" maxlength="255" />
					</view>
					<!-- 指派生产方 -->
					<view class="form-item" v-if="state.form.userType==4">
						<view class="form-label">指派生产方</view>
						<uni-data-select v-model="state.form.assigned" :localdata="state.producerList">
						</uni-data-select>
					</view>

					<!-- 备注 -->
					<view class="form-item">
						<view class="form-label">备注</view>
						<textarea class="form-textarea" placeholder="请输入备注信息" v-model="state.form.remark"
							maxlength="500" :show-count="true" />
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-section">
				<button class="submit-btn" @click="onSubmit" :loading="state.submitting">
					{{ state.submitting ? '保存中...' : '保存' }}
				</button>
			</view>
		</view>
	</s-layout>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		computed
	} from 'vue';
	import AgentApi from '@/sheep/api/agent/agent';
	import DictApi from '@/sheep/api/system/dict';
	const state = reactive({
		form: {
			id: null,
			memberId: '',
			adminId: '',
			userType: 4,
			agentLevel: '',
			userName: '',
			mobile: '',
			address: '',
			status: true,
			remark: '',
			creator: '',
			creatorName: '',
			updaterName: '',
			assigned: ''
		},
		isAdmin: false,
		adminIdIndex: null,
		agentLevelIndex: null,
		submitting: false,
		agentLevelOptions: [],
		userTypeOptions: [{
				text: '生产方',
				value: 3,
				disable:false
			},
			{
				text: '代理商',
				value: 4
			},
		],
		producerList: []
	});
	// 是否为编辑模式
	const isEdit = computed(() => !!state.form.id);
	// 获取等级字典数据
	async function getLevelOptions() {
		try {
			let {
				code,
				data
			} = await DictApi.getDictDataListByType('agent_level');
			if (code === 0 && data) {
				state.agentLevelOptions = data.map(item => ({
					value: Number(item.value), // 使用 id 作为 value
					text: item.label // 使用 name 作为 text
				}));
			}
		} catch (error) {
			console.error('获取等级字典失败:', error);
		}
	}

	async function getProducerList() {
		try {
			let {
				code,
				data
			} = await AgentApi.getProduceList({});
			if (code === 0 && data) {
				state.producerList = data.map(item => ({
					value: item.id, // 使用 id 作为 value
					text: item.userName // 使用 name 作为 text
				}));
			}
		} catch (error) {
			console.error('获取生产方列表失败:', error);
		}
	}

	//查询是否是管理员
	async function getIsAdmin() {
		try {
			let {
				code,
				data
			} = await AgentApi.getIsAdmin();
			if (code === 0) {
				state.isAdmin = data;
				if(!data){
					state.userTypeOptions = [
						{
							text: '生产方',
							value: 3,
							disable:!state.isAdmin
						},
						{
							text: '代理商',
							value: 4
						},
					]
				}
			}
		} catch (error) {
			console.error('获取生产方列表失败:', error);
		}
	}
	onLoad(async (options) => {
		// 获取代理商等级字典数据
		await getLevelOptions();
		// 获取生产方列表
		await getProducerList();
		// 获取是否是管理员
		await getIsAdmin();
		// 获取代理商详情
		if (options.id) {
			await getAgentDetail(options.id);
		}
	});


	// 表单验证
	function validateForm() {


		if (!state.form.userName.trim()) {
			uni.showToast({
				title: '请输入用户名称',
				icon: 'error'
			});
			return false;
		}
		if(!state.form.userType){
			uni.showToast({
				title: '请输入用户类型',
				icon: 'error'
			});
			return false;
		}

		if(state.form.userType==4 && !state.form.agentLevel){
			uni.showToast({
				title: '请输选择供应商等级',
				icon: 'error'
			});
			return false;
		}

		if (!state.form.mobile.trim()) {
			uni.showToast({
				title: '请输入手机号',
				icon: 'error'
			});
			return false;
		}

		// 手机号格式验证
		const mobileReg = /^1[3-9]\d{9}$/;
		if (!mobileReg.test(state.form.mobile)) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'error'
			});
			return false;
		}

		return true;
	}

	// 提交表单
	async function onSubmit() {
		if (!validateForm()) {
			return;
		}

		state.submitting = true;

		try {
			// 构建提交数据
			const submitData = {
				id:state.form.id,
				memberId: state.form.memberId ? parseInt(state.form.memberId) : null,
				adminId: state.form.adminId ? parseInt(state.form.adminId) : null,
				agentLevel: state.form.agentLevel ? parseInt(state.form.agentLevel) : null,
				userName: state.form.userName.trim(),
				mobile: state.form.mobile.trim(),
				address: state.form.address.trim(),
				status: state.form.status,
				remark: state.form.remark.trim(),
				creator: state.form.creator.trim(),
				creatorName: state.form.creatorName.trim(),
				updaterName: state.form.updaterName.trim(),
				assigned: state.form.assigned ? parseInt(state.form.assigned) : null,
				userType: state.form.userType ? parseInt(state.form.userType) : null
			};

			let result;
			if (isEdit.value) {
				// 编辑代理商
				result = await AgentApi.updateAgent( submitData);
			} else {
				// 新增代理商
				result = await AgentApi.createAgent(submitData);
			}

			if (result.code === 0) {
				uni.showToast({
					title: isEdit.value ? '更新成功' : '创建成功',
					icon: 'success'
				});

				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} else {
				uni.showToast({
					title: result.msg || '操作失败',
					icon: 'error'
				});
			}
		} catch (error) {
			uni.showToast({
				title: '操作失败',
				icon: 'error'
			});
		} finally {
			state.submitting = false;
		}
	}

	// 获取代理商详情
	async function getAgentDetail(agentId) {
		try {
			let {
				code,
				data
			} = await AgentApi.getAgent({id:agentId});
			if (code === 0) {
				// 填充表单数据
				state.form.id = data.id;
				state.form.memberId = data.memberId || '';
				state.form.adminId = data.adminId || '';
				state.form.agentLevel = data.agentLevel || '';
				state.form.userName = data.userName || '';
				state.form.mobile = data.mobile || '';
				state.form.address = data.address || '';
				state.form.status = data.status !== false;
				state.form.remark = data.remark || '';
				state.form.creator = data.creator || '';
				state.form.creatorName = data.creatorName || '';
				state.form.updaterName = data.updaterName || '';
				state.form.assigned = data.assigned || '';
			}
		} catch (error) {
			uni.showToast({
				title: '获取代理商信息失败',
				icon: 'error'
			});
		}
	}
</script>

<style lang="scss" scoped>
	/* 方法1：使用 ::v-deep (兼容性更好) */
	::v-deep .uni-select__input-placeholder {
		font-size: 28rpx !important;
	}

	/* 方法2：新版 Vue 可用 :deep() */
	:deep(.uni-select) {
		height: 80rpx !important;
		border: 2rpx solid #e5e5e5 !important;
	}

	.form-container {
		padding: 20rpx;
	}

	.form-section {
		background: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.section-title {
		padding: 30rpx;
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		background: #f8f9fa;
		border-bottom: 2rpx solid #e9ecef;
	}

	.form-content {
		padding: 30rpx;
	}

	.form-item {
		margin-bottom: 40rpx;

		&:last-child {
			margin-bottom: 0;
		}

		&.required .form-label::after {
			content: '*';
			color: #ff4d4f;
			margin-left: 4rpx;
		}
	}

	.form-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		font-weight: 500;
	}

	.form-input {
		height: 80rpx;
		padding: 0 20rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
		font-size: 28rpx;
		background: #fff;

		&:focus {
			border-color: #007aff;
		}
	}

	.form-picker {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
		background: #fff;

		.picker-text {
			height: 100%;
			line-height: 80rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
			color: #333;

			&.placeholder {
				color: #999;
			}
		}
	}

	.form-textarea {
		width: 610rpx;
		min-height: 120rpx;
		padding: 20rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
		font-size: 28rpx;
		background: #fff;

		&:focus {
			border-color: #007aff;
		}
	}

	.switch-text {
		margin-left: 20rpx;
		font-size: 28rpx;
		color: #333;
	}

	.submit-section {
		padding: 40rpx 0;

		.submit-btn {
			width: 100%;
			height: 88rpx;
			background: #007aff;
			color: #fff;
			border-radius: 8rpx;
			font-size: 32rpx;
			font-weight: 600;
			border: none;

			&:disabled {
				background: #ccc;
			}
		}
	}
</style>
